package com.venus.lms.controller;

import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.venus.lms.mapper.UserMapper;
import com.venus.lms.pojo.LoginUser;
import com.venus.lms.pojo.User;
import com.venus.lms.utils.RegexUtils;
import com.venus.lms.utils.Result;
import com.venus.lms.utils.SmsUtils;
import com.venus.lms.utils.TokenUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 学生控制层
 *
 * @author DQM
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取短信验证码
     */
    @GetMapping("/getcode")
    public Result<?> getcode(@RequestParam String phone) {
        //校验手机号格式
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.error("-1", "手机号错误");
        }
        //生成六位随机验证码
        String code = RandomUtil.randomNumbers(6);
        //将验证码存入redis，5分钟有效
        stringRedisTemplate.opsForValue().set(phone, code, 5L, TimeUnit.MINUTES);
        try {
            //阿里云短信服务发送验证码
            SmsUtils.sendSms(phone, code);
        } catch (ClientException e) {
            return Result.error("-1", "验证码服务异常");
        }
        System.out.println(code);
        return Result.success();
    }

    /**
     * 注册功能
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res != null) {
            return Result.error("-1", "用户名已重复");
        }
        userMapper.insert(user);
        return Result.success();
    }

    /**
     * 登录功能
     */
    @CrossOrigin
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().
                eq(User::getUsername, user.getUsername()).
                eq(User::getPassword, user.getPassword()));
        if (res == null) {
            return Result.error("-1", "用户名或密码错误");
        }
        String token = TokenUtils.genToken(res);
        res.setToken(token);
        //访问人数加一
        LoginUser.addVisitCount();
        return Result.success(res);
    }

    /**
     * 添加用户
     */
    @PostMapping
    public Result<?> save(@RequestBody User user) {
        if (user.getPassword() == null) {
            //默认密码为123456
            user.setPassword("123456");
        }
        userMapper.insert(user);
        return Result.success();
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public Result<?> update(@RequestParam Integer id,
                            @RequestParam String password2) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        User user = new User();
        user.setPassword(password2);
        userMapper.update(user, updateWrapper);
        return Result.success();
    }

    /**
     * 修改手机号
     */
    @PutMapping
    public Result<?> password(@RequestBody User user) {
        String code = stringRedisTemplate.opsForValue().get(user.getPhone());  //从redis中取出验证码
        if (code == null) {
            return Result.error("-1", "请先获取验证码");
        }
        if (user.getCode().equals(code)) {
            userMapper.updateById(user);
            stringRedisTemplate.delete(user.getPhone());
            return Result.success();
        }
        return Result.error("-1", "验证码错误");
    }

    /**
     * 修改用户信息
     */
    @PutMapping("/update")
    public Result<?> update(@RequestBody User user) {
        //校验手机号
        if (RegexUtils.isPhoneInvalid(user.getPhone())) {
            return Result.error("-1", "手机号格式错误");
        }
        userMapper.updateById(user);
        return Result.success();
    }

    /**
     * 批量删除用户
     */
    @PostMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestBody List<Integer> ids) {
        userMapper.deleteBatchIds(ids);
        return Result.success();
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        userMapper.deleteById(id);
        return Result.success();
    }

    /**
     * 赋予用户借阅权限
     */
    @PutMapping("/{id}")
    public Result<?> update(@PathVariable Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return Result.error("-1", "授权失败,用户信息错误");
        }
        if (user.getAlow() == null || user.getAlow().equals("-1")) {
            user.setAlow("1");
            userMapper.updateById(user);
            return Result.success();
        }
        if (user.getAlow().equals("1")) {
            return Result.error("-1", "该用户已有借阅权限");
        }
        return Result.error("-1", "服务器错误");
    }

    /**
     * 学生用户分页展示
     *
     * @param pageNum  当前页
     * @param pageSize 一页几条数据
     * @param search   用户真实姓名
     */
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<User> wrappers = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(search)) {
            wrappers.like(User::getNickName, search);
        }
        wrappers.like(User::getRole, 2);  //查找学生用户
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), wrappers);
        return Result.success(userPage);
    }

    /**
     * 学生用户分页展示
     *
     * @param pageNum  当前页
     * @param pageSize 一页几条数据
     * @param search1  id
     * @param search2  真实姓名
     * @param search3  电话
     * @param search4  住址
     */
    @GetMapping("/usersearch")
    public Result<?> findPage2(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               @RequestParam(defaultValue = "") String search1,
                               @RequestParam(defaultValue = "") String search2,
                               @RequestParam(defaultValue = "") String search3,
                               @RequestParam(defaultValue = "") String search4) {
        LambdaQueryWrapper<User> wrappers = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(search1)) {
            wrappers.like(User::getId, search1);
        }
        if (StringUtils.isNotBlank(search2)) {
            wrappers.like(User::getNickName, search2);
        }
        if (StringUtils.isNotBlank(search3)) {
            wrappers.like(User::getPhone, search3);
        }
        if (StringUtils.isNotBlank(search4)) {
            wrappers.like(User::getAddress, search4);
        }
        wrappers.like(User::getRole, 2);
        wrappers.orderByAsc(User::getId);   //按编号排序
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), wrappers);
        return Result.success(userPage);
    }

    /**
     * 判断是否有借阅权利
     */
    @GetMapping("/alow/{id}")
    public Result<?> alow(@PathVariable Long id) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(User::getId, id).eq(User::getAlow, "1");
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            return Result.error("-1", "您没有被管理员授予借阅权!");
        }
        return Result.success();
    }

    /**
     * 根据学生姓名获取学生
     */
    @GetMapping("/borrow/{name}")
    public Result<?> getUserByName(@PathVariable String name) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(User::getNickName, name).eq(User::getRole, "2");
        User user = userMapper.selectOne(wrapper);
        return Result.success(user);
    }

    /**
     * 取消借阅权利
     */
    @PutMapping("/cancelAlow/{id}")
    public Result<?> cancelAlow(@PathVariable Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return Result.error("-1", "用户信息错误");
        }
        if (user.getAlow().equals("1")) {
            user.setAlow("-1");
            userMapper.updateById(user);
            return Result.success();
        }
        if (user.getAlow() == null) {
            return Result.error("-1", "该用户已没有借阅权限");
        }
        return Result.error("-1", "服务器错误");
    }
}
